package com.awenhui.demo.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 *
 * 自定义realm
 * @author yuxf
 * @version 1.0
 * @date 2020/12/21 16:10
 */
public class ShrioRealm extends AuthorizingRealm {


    @Autowired
    TestShiroUserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //从数据库取角色
        Set<String> roles = userService.getRoles();
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();//权限信息
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermission("user:create");
        return  simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if(token.getPrincipal()==null)return null;
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //String userName=token.getPrincipal().toString();
        String userName=upToken.getUsername();
        //从数据库查询用信息
        UserDto userDto = userService.loadUserByUserName(userName);
        if(userDto==null||"".equals(userDto.getUserName())) throw  new UnknownAccountException();
        //密码盐
        ByteSource salt = ByteSource.Util.bytes(userDto.getSalt());

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userDto, userDto.getPassword(), salt,getName());
        return simpleAuthenticationInfo;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456", "abc", 2);
        String password = md5Hash.toHex();
        System.out.println(password);

    }
}
